<template>
  <div class="container">
    <div class="header" style="background-image: url(static/img/background.png)">
      <div class="head-top">
        <span>交易记录</span>
        <img @click="$router.push({name:'Index'})" src="static/img/w-left.png" />
      </div>
      <div class="head-cen">
        <div class="name" style="margin-top:.2rem;">
          <span>{{coin.name}}</span>
        </div>

        <div class="name">
          <span>可用:{{convertBigNumber(accDiv(coin.balance,Math.pow(10,coin.decimals)))}}</span>
        </div>

        <div class="name">
          <span>冻结:{{convertBigNumber(accDiv(coin.balance,Math.pow(10,coin.decimals)))}}</span>
        </div>
      </div>
      <div class="head-btm">
        <div class="b-btn" @click="$router.replace({name:'TransactionTo',params:{symbol:'ETH'}})">
          <img src="static/img/trans.png" alt />
          <span>转账</span>
        </div>
        <div
          class="b-btn right-btn"
          @click="$router.push({name:'EthReceiptCode',params:{symbol:'ETH'}})"
        >
          <img src="static/img/qrcode.png" alt />
          <span>收款</span>
        </div>
      </div>
    </div>
    <div style="position: absolute;left:46%;top:40%" v-if="isLoading">
      <van-loading type="spinner" color="#65686C" />
    </div>
    <div style="position: absolute;left:46%;top:40%" v-if="isLoading">
      <van-loading type="spinner" color="#65686C" />
    </div>
    <div style="overflow-x:hidden;max-height: 70%">
      <div class="hint">
        <span>交易记录</span>
        <div @click="goDetail">
          <img class="detail" src="static/img/detail.png" alt />
          <span>详细信息</span>
          <img class="b-right" src="static/img/b-right.png" alt />
        </div>
      </div>
      <div id="tranList">
        <div
          class="tran"
          v-for="(tran,index) in tranList"
          :key="index"
          @click="$router.push({name:'TransactionInfo',params:{index:index,tran:tran,coin:coin}})"
        >
          <div class="left">
            <img v-if="!tran.get" src="static/img/out.png" />
            <img v-if="tran.get" src="static/img/enter.png" />
            <div>
              <div class="add">{{tran.toAddress}}</div>
              <div class="date">{{tran.date}}</div>
            </div>
          </div>
          <div class="right">
            <div
              class="out"
              v-if="!tran.get"
            >-{{accDiv(tran.value,Math.pow(10,tran.decimals))}} {{symbol?symbol.toLowerCase():''}}</div>
            <div
              class="enter"
              v-if="tran.get"
            >{{accDiv(tran.value,Math.pow(10,tran.decimals))}} {{symbol?symbol.toLowerCase():''}}</div>
            <div class="out" v-if="tran.timeout">交易失败</div>
            <div class="enter" v-if="tran.error">等待打包</div>
          </div>
        </div>
      </div>

      <div
        v-if="tranList.length<1"
        style="position: absolute;top:50%;font-size: 1.3rem;color:gray;left:49%"
      >~</div>
    </div>
  </div>
</template>


<script>
import { Loading } from "vant";

import BigNumber from "bignumber.js";

import { mapGetters, mapActions } from "vuex";
import { etherscanAK,mainCoinList } from "../../service/eth/config";
import axios from "axios";
import {} from "mint-ui";

export default {
  components: {},
  data() {
    return {
      isLoading: true,
      symbol: "",
      coin: "",
      tranList: [],
      decimals: 0,
      chartsData: {},
    };
  },
  created() {
    console.log(this.$route);
    console.log(this.currentAccount);
    this.symbol = this.currentAccount.currentCoin.name;
    this.coin = this.currentAccount.currentCoin;
    console.log(this.coin);
    let list = [].concat(this.currentAccount.coins[this.coin.name]);
    if (list[0]) {
      this.tranList = list.reverse();
    } else {
      list = [];
    }
  },
  computed: {
    ...mapGetters([
      "currentAccount",
      "wallet",
      "accountIndex",
      "messageList",
      "ethBaseNet",
    ]),
  },
  methods: {
    ...mapActions(["setWallet", "set", "setAccountIndex"]),
    openScan() {
      this.$router.push({ name: "Scan", params: { coin: this.coin } });
    },
    accMul(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).multipliedBy(arg2).valueOf()
      );
    },
    accDiv(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).dividedBy(arg2).valueOf()
      );
    },
    convertBigNumber: (param) => {
      let strParam = String(param);
      let flag = /e/.test(strParam);
      if (!flag) return param;

      // 指数符号 true: 正，false: 负
      let sysbol = true;
      if (/e-/.test(strParam)) {
        sysbol = false;
      }
      // 指数
      let index = Number(strParam.match(/\d+$/)[0]);
      // 基数
      let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, "");

      if (sysbol) {
        return basis.padEnd(index + 1, 0);
      } else {
        return basis.padStart(index + basis.length, 0).replace(/^0/, "0.");
      }
    },
    formatDateTime(inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    goDetail() {
      let contractaddress = "";
      for (let i = 0; i < mainCoinList.length; i++) {
        if (mainCoinList[i].name == this.coin.name) {
          contractaddress = mainCoinList[i].contractaddress;
          console.log("mainCoinList[i].contractaddress");
        }
      }
      let url = `https://cn.etherscan.com/token/${contractaddress}?a=${this.currentAccount.address}`;
      window.location.href = url;
    },
    getTransactionList() {
      if (this.$route.params.dontRefresh) {
        this.isLoading = false;
        return;
      }
      let _this = this;
      let oldTranList = [].concat(this.currentAccount.coins[this.coin.name]);
      let date = (new Date().getTime() + "").substring(0, 10);

      _this.decimals = _this.coin.decimals;

      let url =
        "http://api-cn.etherscan.com/api?module=account&action=tokentx&contractaddress=" +
        _this.coin.address +
        "&address=" +
        this.currentAccount.address +
        "&page=1&offset=9999&sort=asc&apikey=" +
        etherscanAK;
      console.log(url);
      axios.get(url).then((resp) => {
        console.log(resp);
        if (resp.status == "200") {
          let list = resp.data.result;

          let transactionList = [];

          if (
            list.length > oldTranList.length &&
            !_this.$route.params.dontRefresh
          ) {
            for (let i = 0; i < list.length; i++) {
              let obj = list[i];
              console.log(obj);
              let tran = {
                fromAddress: obj.from,
                toAddress: obj.to,
                img: "",
                name: _this.coin.name,
                error: false,
                get: false,
                txhash: obj.hash,
                decimals: _this.coin.decimals,
                blockNumber: obj.blockNumber,
                blockHash: obj.blockHash,
                date: this.formatDateTime(obj.timeStamp),
                timeStamp: obj.timeStamp,
                value: parseInt(obj.value),
                gasMoney: this.global.web3.utils.fromWei(
                  parseInt(obj.gasUsed) * parseInt(obj.gasPrice) + "",
                  "ether"
                ),
                input: obj.input,
                pending: false,
                decimals: _this.decimals,
              };

              if (obj.txreceipt_status == "0" || obj.isError == "1") {
                // tran.error = true;
                tran.img = "static/img/error.png";
              } else if (
                obj.from == _this.currentAccount.address.toLowerCase() &&
                obj.to
              ) {
                tran.img = "static/img/to2.png";
              } else if (
                obj.from != _this.currentAccount.address.toLowerCase()
              ) {
                tran.get = true;
                tran.img = "static/img/from.png";
              }
              console.log(
                _this.convertBigNumber(tran.value / Math.pow(10, tran.decimals))
              );
              let timeStamp = parseInt(obj.timeStamp);
              let subtract = date - timeStamp;
              if (subtract < 1) {
                tran.date = "1秒前";
              } else if (subtract < 60) {
                tran.date = subtract.toFixed(0) + "秒前";
              } else if (subtract < 60 * 60) {
                tran.date = (subtract / 60).toFixed(0) + " 分前";
              } else if (subtract > 60 * 60 && subtract < 60 * 60 * 24) {
                tran.date = (subtract / 60 / 60).toFixed(0) + " 小时前";
              } else if (
                subtract > 60 * 60 * 24 &&
                subtract < 60 * 60 * 24 * 30
              ) {
                tran.date = (subtract / 60 / 60 / 24).toFixed(0) + " 日前";
              } else {
                tran.date = this.formatDateTime(timeStamp * 1000);
              }
              transactionList.push(tran);
            }

            this.currentAccount.coins[this.coin.name] = transactionList;
            this.wallet[this.accountIndex] = this.currentAccount;
            this.setWallet(this.wallet);
            this.tranList = [].concat(transactionList).reverse();
          } else {
            let d = new Date().getTime();
            for (let j = 0; j < oldTranList.length; j++) {
              let oldObj = oldTranList[j];
              let newObj = j < list.length ? list[j] : null;
              let tran = {};
              if (newObj) {
                tran = {
                  fromAddress: newObj.from,
                  toAddress: newObj.to,
                  img: "",
                  name: _this.coin.name,
                  error: false,
                  get: false,
                  decimals: _this.coin.decimals,
                  txhash: newObj.hash,
                  blockNumber: newObj.blockNumber,
                  blockHash: newObj.blockHash,
                  date: this.formatDateTime(newObj.timeStamp),
                  timeStamp: newObj.timeStamp,
                  timeout: false,
                  value: parseInt(newObj.value),
                  gasMoney: this.global.web3.utils.fromWei(
                    parseInt(newObj.gasUsed) * parseInt(newObj.gasPrice) + "",
                    "ether"
                  ),
                  input: newObj.input,
                  pending: false,
                  decimals: _this.decimals,
                };

                if (newObj.txreceipt_status == "0") {
                  //  tran.error = true;
                  tran.img = "static/img/error.png";
                } else if (
                  newObj.from == _this.currentAccount.address.toLowerCase() &&
                  newObj.to
                ) {
                  tran.img = "static/img/to2.png";
                } else if (
                  newObj.from != _this.currentAccount.address.toLowerCase()
                ) {
                  tran.get = true;
                  tran.img = "static/img/from.png";
                }

                console.log(
                  _this.convertBigNumber(
                    tran.value / Math.pow(10, tran.decimals)
                  )
                );
                let timeStamp = parseInt(newObj.timeStamp);
                let subtract = date - timeStamp;
                if (subtract < 1) {
                  tran.date = "1秒前";
                } else if (subtract < 60) {
                  tran.date = subtract.toFixed(0) + "秒前";
                } else if (subtract < 60 * 60) {
                  tran.date = (subtract / 60).toFixed(0) + " 分前";
                } else if (subtract > 60 * 60 && subtract < 60 * 60 * 24) {
                  tran.date = (subtract / 60 / 60).toFixed(0) + " 小时前";
                } else if (
                  subtract > 60 * 60 * 24 &&
                  subtract < 60 * 60 * 24 * 30
                ) {
                  tran.date = (subtract / 60 / 60 / 24).toFixed(0) + " 日前";
                } else {
                  tran.date = this.formatDateTime(timeStamp * 1000);
                }
              } else {
                tran = oldObj;

                if (!oldObj) continue;
                let timeStamp = parseInt(tran.timeStamp);

                if (new Date().getTime() / 1000 - timeStamp > 75) {
                  tran.timeout = true;
                }
                let subtract = date - timeStamp;

                if (subtract < 1) {
                  tran.date = "1秒前";
                } else if (subtract < 60) {
                  tran.date = subtract.toFixed(0) + "秒前";
                } else if (subtract < 60 * 60) {
                  tran.date = (subtract / 60).toFixed(0) + " 分前";
                } else if (subtract > 60 * 60 && subtract < 60 * 60 * 24) {
                  tran.date = (subtract / 60 / 60).toFixed(0) + " 小时前";
                } else if (
                  subtract > 60 * 60 * 24 &&
                  subtract < 60 * 60 * 24 * 30
                ) {
                  tran.date = (subtract / 60 / 60 / 24).toFixed(0) + " 日前";
                } else {
                  tran.date = this.formatDateTime(timeStamp * 1000);
                }
              }
              transactionList.push(tran);
            }

            this.currentAccount.coins[this.coin.name] = transactionList;
            this.wallet[this.accountIndex] = this.currentAccount;
            this.setWallet(this.wallet);
            this.tranList = [].concat(transactionList).reverse();
          }
        }
        this.isLoading = false;
      });
    },
  },
  async mounted() {
    let _this = this;
    if (_this.global.web3 == "") {
      let fdStart = _this.currentAccount.priKey.indexOf("0x");
      if (fdStart != -1) {
        this.currentAccount.priKey = _this.currentAccount.priKey.substring(
          2,
          _this.currentAccount.priKey.length
        );
      }
      accountUtils
        .initProviderFromPrivateKey(
          _this.currentAccount.priKey,
          _this.global.infuraAK
        )
        .then((provide) => {
          accountUtils
            .initWeb3FromProvider(provide)
            .then(({ web3, provider, priKey, pubKey, address }) => {
              _this.global.setWeb3(web3);
              _this.getTransactionList();
            });
        });
    } else {
      this.getTransactionList();
    }
  },
  watch: {},
};
</script>
<style lang="less" scoped>
@import url("../../assets/css/transactionERC.less");
</style>

